/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 10/06/2004
 * Time: 20:19:41
 */
package com.talios.jira.idea.intentions;

import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.util.IncorrectOperationException;
import com.talios.jira.browser.signals.JiraServerDetails;
import com.talios.jira.idea.JiraConfigurationComponent;
import com.talios.jira.idea.PsiUtils;

public class JiraIssueBrowseIntention extends AnnotatedIssueCommentIntention {
    private static final Logger LOGGER = Logger.getInstance("Jira Browser");

    private final Project myProject;

    public JiraIssueBrowseIntention(Project project) {
        myProject = project;
    }

    public void projectOpened() {
    }

    public void projectClosed() {
    }

    public String getComponentName() {
        return "JiraIssueBrowseIntention";
    }

    public void initComponent() {
        IntentionManager.getInstance(myProject).addAction(this);
    }

    public void disposeComponent() {
    }

    public String getText() {
        return "View " + issueKey + " in browser";
    }

    public String getFamilyName() {
        return getText();
    }

    public void invoke(Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {

        int offset = editor.getCaretModel().getOffset();
        PsiElement element = psiFile.findElementAt(offset);

        if (element instanceof PsiDocToken || element instanceof PsiComment) {
            if (element instanceof PsiDocToken) {
                element = PsiUtils.findParentPsiElement(element, PsiComment.class);
            }

            PsiComment comment = (PsiComment) element;

            String issueKey = getIssueKeyFromComment(comment.getText());

            if (issueKey != null) {
                JiraConfigurationComponent config = project.getComponent(JiraConfigurationComponent.class);

                String browser = config.getBrowserExecutable();

                JiraServerDetails server = config.findServerForIssueKey(issueKey);
                if (server != null) {
                    LOGGER.info("Viewing " + issueKey + " at " + server.getBaseurl());
                    server.viewIssueInBrowser(browser, issueKey);
                }
            }
        }
    }

    public boolean startInWriteAction() {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
